from wx import wx
import StringIO
import AddImageDialog
import EditImageProperties
import sqlite3
import base64
import Image
import CropImageDialog
import RotateImageDialog
import ResizeImageDialog

class CreateImageTab(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        
        self.toolbar_ADDIMAGE = wx.NewId()
        self.toolbar_DELIMAGE = wx.NewId()
        self.toolbar_CROPIMAGE = wx.NewId()
        self.toolbar_RESIZEIMAGE = wx.NewId()
        self.toolbar_ROTATEIMAGE = wx.NewId()
        self.toolbar_EDITPROP = wx.NewId()
        
        self.imageFilePath = ""
        
        self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))
        self.imageViewer = wx.Panel(self, style=wx.BORDER_SUNKEN)
        self.imageViewer.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
        self.imageListBox = wx.ListBox(self, -1,size=wx.Size(100,-1), style=wx.BORDER_SUNKEN | wx.LB_SINGLE | wx.LB_NEEDED_SB)
        self.imageToolbar = self.MakeImageToolbar()
        self.mainBox = wx.BoxSizer(wx.VERTICAL)
        self.botBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox.Add(self.imageToolbar, 1, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.imageListBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.imageViewer, 1, wx.EXPAND)
        self.mainBox.Add(self.topBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.mainBox.Add(self.botBox, 1, wx.EXPAND)
        self.SetSizer(self.mainBox)
        
        wx.EVT_LISTBOX(self, self.imageListBox.GetId(), self.OnSelectedImageItem)
        
    def MakeImageToolbar(self):
        tb = wx.ToolBar(self, -1, style=wx.TB_FLAT | wx.NO_BORDER)
        tb.AddTool(self.toolbar_ADDIMAGE, wx.Bitmap("images/list-add.png", wx.BITMAP_TYPE_PNG), shortHelpString="Add Image")
        tb.AddTool(self.toolbar_DELIMAGE, wx.Bitmap("images/list-remove.png", wx.BITMAP_TYPE_PNG), shortHelpString="Remove Selected Image")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_RESIZEIMAGE, wx.Bitmap("images/transform-scale.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/transform-scale-off.png", wx.BITMAP_TYPE_PNG), shortHelpString="Resize Selected Image")
        tb.AddTool(self.toolbar_CROPIMAGE, wx.Bitmap("images/transform-crop-and-resize.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/transform-crop-and-resize-off.png", wx.BITMAP_TYPE_PNG), shortHelpString="Crop Selected Image")
        tb.AddTool(self.toolbar_ROTATEIMAGE, wx.Bitmap("images/transform-rotate.png", wx.BITMAP_TYPE_PNG), wx.Bitmap("images/transform-rotate-off.png", wx.BITMAP_TYPE_PNG), shortHelpString="Rotate Selected Image")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_EDITPROP, wx.Bitmap("images/document-properties.png", wx.BITMAP_TYPE_PNG), shortHelpString="Edit Image Properties")
        # crop, resize, rotate, lines, free lines
        
        tb.EnableTool(self.toolbar_DELIMAGE, False)
        tb.EnableTool(self.toolbar_CROPIMAGE, False)
        tb.EnableTool(self.toolbar_RESIZEIMAGE, False)
        tb.EnableTool(self.toolbar_ROTATEIMAGE, False)
        tb.EnableTool(self.toolbar_EDITPROP, False)
        
        wx.EVT_TOOL(self, self.toolbar_ADDIMAGE, self.AddImage)
        wx.EVT_TOOL(self, self.toolbar_DELIMAGE, self.DelImage)
        wx.EVT_TOOL(self, self.toolbar_CROPIMAGE, self.CropImage)
        wx.EVT_TOOL(self, self.toolbar_RESIZEIMAGE, self.ResizeImage)
        wx.EVT_TOOL(self, self.toolbar_ROTATEIMAGE, self.RotateImage)
        wx.EVT_TOOL(self, self.toolbar_EDITPROP, self.EditProperties)
        
        tb.Realize()
        
        return tb
        
    def OnSelectedImageItem(self, event):
        if(self.imageListBox.GetSelection() != -1):
            self.imageToolbar.EnableTool(self.toolbar_DELIMAGE, True)
            self.imageToolbar.EnableTool(self.toolbar_CROPIMAGE, True)
            self.imageToolbar.EnableTool(self.toolbar_RESIZEIMAGE, True)
            self.imageToolbar.EnableTool(self.toolbar_ROTATEIMAGE, True)
            self.imageToolbar.EnableTool(self.toolbar_EDITPROP, True)
            
            self.imageViewer.DestroyChildren()

            self.inString = StringIO.StringIO()
            tmpString = self.imageListBox.GetStringSelection()
            tmpString2 = tmpString.split(".", 1)
            self.data = base64.decodestring(self.TopLevelParent.currentImageDict[int(tmpString2[0])][0])
            self.inString.flush()
            self.inString.write(self.data)
            self.inString.seek(0)
            self.originalImage = Image.open(self.inString)
            self.ShowBitmapFromPIL(self.imageViewer, self.originalImage)
            self.inString.close()
            self.TopLevelParent.DisplayDebug("load image here...")

    def EditProperties(self, event):
        self.TopLevelParent.DisplayDebug("edit here")
        self.editImageProperties = EditImageProperties.EditImageProperties(self, -1, "Edit Image Properties", size=(550, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.editImageProperties.CenterOnParent()
        tmpString = self.imageListBox.GetStringSelection() # get selected item
        tmpId = int(tmpString.split(".", 1)[0]) # extract resourceID
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("SELECT layout FROM ResourceTable WHERE resourceID = (?)", (tmpId,))
        for row in cur:
            selectedLayout = row[0].split("::")
            self.editImageProperties.imageAltText.SetValue(selectedLayout[0])
            self.editImageProperties.imageTitleText.SetValue(selectedLayout[1])
        con.close()
        
        if(self.editImageProperties.ShowModal() == wx.ID_OK):
            self.layoutValue = self.editImageProperties.imageAltText.GetValue() + "::" + self.editImageProperties.imageTitleText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("UPDATE ResourceTable SET layout = (?) WHERE resourceID = (?)", (self.layoutValue, tmpId))
            con.commit()
            con.close()
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
            self.TopLevelParent.DisplayDebug("ok")
        else:
            self.TopLevelParent.DisplayDebug("cancel")
        
        self.editImageProperties.Destroy()
        
    def AddImage(self, event):
        self.addImageDialog = AddImageDialog.AddImageDialog(self, -1, "Add Image to Course", size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addImageDialog.CenterOnParent()
        
        if(self.addImageDialog.ShowModal() == wx.ID_OK):
            self.data = open(self.TopLevelParent.opj(self.addImageDialog.imageFileText.GetValue()), "rb").read()
            self.layoutValue =  self.addImageDialog.imageAltText.GetValue() + "::" + self.addImageDialog.imageTitleText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("INSERT INTO ResourceTable(resourceTypeID, layout, resourceData, courseID) VALUES(2, ?, ?, ?)", (self.layoutValue, base64.encodestring(sqlite3.Binary(self.data)), self.TopLevelParent.currentCourseID))
            con.commit()
            con.close()
            # write the data to db...
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
            self.TopLevelParent.DisplayDebug("You pressed OK")
            
        else:
            self.TopLevelParent.DisplayDebug("You pressed Cancel")
            
        self.addImageDialog.Destroy()
        
    def DelImage(self, event):
        tmpString = self.imageListBox.GetStringSelection()
        tmpString2 = tmpString.split(".", 1)
        self.imageViewer.DestroyChildren()
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("DELETE FROM ResourceTable WHERE resourceID = (?)", (int(tmpString2[0]),))
        con.commit()
        con.close()
        self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
        self.TopLevelParent.DisplayDebug("image ID " + tmpString2[0] + " deleted")
    
    def CropImage(self, event):
        self.cropImageDialog = CropImageDialog.CropImageDialog(self, -1, "Crop Selected Image", size=(150, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.cropImageDialog.CenterOnParent()
        if(self.cropImageDialog.ShowModal() == wx.ID_OK):
            self.inString = StringIO.StringIO()
            self.outString = StringIO.StringIO()
            tmpString = self.imageListBox.GetStringSelection()
            tmpString2 = tmpString.split(".", 1)
            self.data = base64.decodestring(self.TopLevelParent.currentImageDict[int(tmpString2[0])][0])
            self.inString.write(self.data)
            self.inString.seek(0)
            self.originalImage = Image.open(self.inString)
            self.croppedRegion = self.originalImage.crop((self.cropImageDialog.leftSpinner.GetValue(), self.cropImageDialog.topSpinner.GetValue(), self.originalImage.size[0] - self.cropImageDialog.rightSpinner.GetValue(), self.originalImage.size[1] - self.cropImageDialog.bottomSpinner.GetValue()))
            self.croppedRegion.save(self.outString, "PNG")
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("UPDATE ResourceTable set resourceData = (?) where resourceID = (?)", (base64.encodestring(sqlite3.Binary(self.outString.getvalue())),int(tmpString2[0])))
            con.commit()
            con.close()
            self.ShowBitmapFromPIL(self.imageViewer, self.croppedRegion)
            self.inString.close()
            self.outString.close()
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
        
    def RotateImage(self, event):
        self.rotateImageDialog = RotateImageDialog.RotateImageDialog(self, -1, "Rotate Selected Image", size=(150, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.rotateImageDialog.CenterOnParent()
        if(self.rotateImageDialog.ShowModal() == 5101):
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
            self.TopLevelParent.DisplayDebug("rotated...")
        else:
            self.TopLevelParent.DisplayDebug("error")
        
    def ResizeImage(self, event):
        self.resizeImageDialog = ResizeImageDialog.ResizeImageDialog(self, -1, "Resize Selected Image", size=(150, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.resizeImageDialog.CenterOnParent()
        if(self.resizeImageDialog.ShowModal() == 5101):
            self.TopLevelParent.currentImageDict = self.TopLevelParent.RefreshListBox(self.imageListBox, self.TopLevelParent.currentCourseID, 2, None)
            self.TopLevelParent.DisplayDebug("resize Image")
        else:
            self.TopLevelParent.DisplayDebug("error")

    def ShowBitmapFromStream(self, bmpStream): # when pull image from DB
        self.bitmap = wx.StaticBitmap(self.imageViewer, -1, wx.BitmapFromImage(wx.ImageFromStream(bmpStream)))
        self.imageViewer.SetClientSize(self.bitmap.GetSize())
    
    def ShowBitmapFromPIL(self, currentPanel, currentPIL): # when we operate on the image...
        self.wxImg = wx.EmptyImage(currentPIL.size[0], currentPIL.size[1])
        self.wxImg.SetData(currentPIL.convert("RGB").tostring())
        self.wxImg.SetAlphaData(currentPIL.convert("RGBA").tostring()[3::4])
        self.bmpImg = self.wxImg.ConvertToBitmap()
        currentPanel.DestroyChildren()
        self.bmp = wx.StaticBitmap(currentPanel, -1, self.bmpImg, wx.Point(0,0), wx.Size(currentPIL.size[0], currentPIL.size[1]))
        currentPanel.SetClientSize(self.bmp.GetSize())
